package com.itmk.web.sys_notice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itmk.utils.ResultUtils;
import com.itmk.utils.ResultVo;


import com.itmk.web.sys_notice.entity.SysNotice;
import com.itmk.web.sys_notice.entity.SysNoticePageParm;
import com.itmk.web.sys_notice.service.SysNoticeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/api/sysNotice")
public class SysNoticeController {
    @Autowired
    private SysNoticeService sysNoticeService;

    @PreAuthorize("hasAuthority('sys:sysNotice:add')")
    @PostMapping("/add")
    public ResultVo add(@RequestBody SysNotice sysNotice){
        sysNotice.setCreateTime(new Date());
        if(sysNoticeService.save(sysNotice)) {
            return ResultUtils.success("新增成功");
        }
        return ResultUtils.success("新增失败");
    }

    //编辑
    @PreAuthorize("hasAuthority('sys:sysNotice:edit')")
    @PutMapping("/edit")
    public ResultVo edit(@RequestBody SysNotice sysNotice){
        if(sysNoticeService.updateById(sysNotice)) {
            return ResultUtils.success("编辑成功");
        }
        return ResultUtils.success("编辑失败");

    }

    //删除
    @PreAuthorize("hasAuthority('sys:sysNotice:delete')")
    @DeleteMapping("/{noticeId}")
    public ResultVo delete(@PathVariable("noticeId") Long noticeId ){
        if(sysNoticeService.removeById(noticeId)) {
            return ResultUtils.success("删除成功");
        }
        return ResultUtils.success("删除失败");


    }

    //列表
    @GetMapping("/list")
    //列表
    public ResultVo list(SysNoticePageParm parm){
        //构造分页对象
        IPage<SysNotice> page = new Page<>(parm.getCurrentPage(),parm.getPageSize());
        //构造查询条件
        QueryWrapper<SysNotice> query = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(parm.getNoticeTitle())){
            query.lambda().like(SysNotice::getNoticeTitle,parm.getNoticeTitle());
        }

        //排序，新的新出
        query.lambda().orderByDesc(SysNotice::getCreateTime);
        IPage<SysNotice> list =sysNoticeService.page(page,query);
        return ResultUtils.success("查询成功",list);
    }
}
